package net.dlz.example.controller;

import net.dlz.example.domain.District;
import net.dlz.example.domain.Street;
import net.dlz.example.service.DistrictService;
import net.dlz.example.service.StreetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/Street")
public class StreetController {
    @Autowired
    private StreetService streetService;
    @Autowired
    DistrictService districtService;

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public String streetPage(Model model){
        List<Street> streets = streetService.listStreet();
        model.addAttribute("streets",streets);
        return "street-list";
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String addStreetPage(Model model){
        model.addAttribute("districts",districtService.selectAllDistrict());
        model.addAttribute("street", new Street());
        return "street-add";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String savaStreet(Street street ){
        int updated = streetService.savaStreet(street);
            return "redirect:/Street/search";
    }

    @GetMapping(value = "/edit")
    public String editStreetPage(@RequestParam("id")String id,Model model){
        Street street = streetService.findStreetByPrimaryKey(id);
        model.addAttribute("districts",districtService.selectAllDistrict());
        model.addAttribute("street",street);
        return "street-add";
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public Boolean deleteStreet(@RequestParam("id") String id){
        int deleted = streetService.deleteStreetByPrimaryKey(id);
        return deleted > 0;
    }

    @RequestMapping("/selectAllDistrict")
    public List<District> selectAllDistrict(Model model){
        List<District> districts = districtService.selectAllDistrict();
        model.addAttribute("districts",districts);
        return districts;
    }

}
